<!DOCTYPE html>
<html lang="en">
<head>
    <title>Chat Example</title>

    <style type="text/css">
        html {
            overflow: hidden;
        }

        body {
            overflow: hidden;
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100%;
            background: gray;
        }

        #log {
            background: white;
            margin: 0;
            padding: 0.5em 0.5em 0.5em 0.5em;
            position: absolute;
            top: 0.5em;
            left: 0.5em;
            right: 0.5em;
            bottom: 3em;
            overflow: auto;
        }

        #form {
            background: white;
            padding: 0 0.5em 0 0.5em;
            margin: 0;
            position: absolute;
            bottom: 1em;
            left: 0px;
            width: 100%;
            overflow: hidden;
        }

    </style>
</head>
<body>
<div id="log"></div>
<form id="form">

    <div id="app">
        <input class="" id="ws-url" value="127.0.0.1:8888/ws">
        <button type="button" @click="link">link</button>
        <button type="button" @click="close">close</button>
        <button type="button" @click="cleanLog">clean-log</button>

        <div class="" style="display: inline-block;margin-left: 100px">
            <select v-model="curCmd" @change="selectCmd($event)">
                <option value="NONE">未选择</option>
                <option v-for="(item,k) in cmd" :key="k" :value="k">
                    #{item.name}
                </option>
            </select>
        </div>

        <button type="button" @click="send">send</button>
        <button type="button" @click="add">add</button>
        <button type="button" @click="clean">clean</button>

        <template v-for="(item,k) in sendForm" :key="k">
            <div>
                <input type="text" size="10" v-model="item.type" placeholder="type"/>
                <input type="text" size="10" v-model="item.name" placeholder="name"/>
                <input type="text" size="80" v-model="item.val" placeholder="val"/>
                <button type="button" @click="del(k)">del</button>
                <button type="button" @click="cleanVal(k)">clean val</button>
            </div>
        </template>
    </div>
</form>


</body>

<!--<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>-->
<script src="./public/vue.js"></script>
<script type="text/javascript">
    const {createApp} = Vue
    let conn;

    function base64DecodeUTF8(base64Str) {
        const binaryStr = atob(base64Str);
        const bytes = new Uint8Array([...binaryStr].map(char => char.charCodeAt(0)));
        const decoder = new TextDecoder('utf-8');
        return decoder.decode(bytes);
    }

    window.onload = function () {
        var cmd = document.getElementById("cmd");
        var msg = document.getElementById("msg");
        var log = document.getElementById("log");

        function appendLog(item) {
            var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
            log.appendChild(item);
            if (doScroll) {
                log.scrollTop = log.scrollHeight - log.clientHeight;
            }
        }

        function link() {
            if (window["WebSocket"]) {
                let wsUrl = document.getElementById("ws-url").value
                console.log("wsUrl",wsUrl)
                if (!wsUrl){
                    alert("no url");
                    return;
                }
                conn = new WebSocket("ws://"+wsUrl);

                conn.onerror = function (error) {
                    console.log('WebSocket Error: ', error);
                };

                conn.onopen = function (evt) {
                    let item = document.createElement("div");
                    item.innerHTML = `<b>connect to ${wsUrl} </b>`;
                    appendLog(item);
                };

                conn.onclose = function (evt) {
                    let item = document.createElement("div");
                    item.innerHTML = "<b>Connection closed.</b>";
                    appendLog(item);
                };

                conn.onmessage = function (evt) {
                    console.log("evt",evt)
                    // let messages = evt.data.split('\n');
                    let rawMsg = evt.data;
                    let msgStr = "";
                    let rawObj = null;
                    let msg = "";
                    try {
                        rawObj = JSON.parse(rawMsg);
                        console.log("cmd",rawObj.Cmd)
                        if (rawObj.Cmd==10){
                            let sendData = {"cmd":11}
                            let sendStr = JSON.stringify(sendData);
                            conn.send(sendStr);
                            return
                        }
                        console.log("1--",rawObj)
                        msgStr = base64DecodeUTF8(rawObj.Data)
                        rawObj.Data = msgStr
                        console.log("2--",rawObj)
                        msg = JSON.stringify(rawObj)
                        console.log("3--",msg)
                    } catch (error) {
                        console.error("解析失败:", error);
                    }

                    let item = document.createElement("div");
                    item.innerText = msg;
                    console.log(rawMsg)
                    console.log(rawObj)
                    console.log(msgStr)
                    console.log(msg)
                    appendLog(item);

                    // for (var i = 0; i < messages.length; i++) {
                    //
                    //     let msg = messages[i];
                    //     // let msg = "";
                    //     // try {
                    //     //     let rawObj = JSON.parse(raw);
                    //     //     let rawData = base64DecodeUTF8(rawObj.Data)
                    //     //     msg = JSON.stringify(rawObj.Data)
                    //     // } catch (error) {
                    //     //     console.error("解析失败:", error);
                    //     // }
                    //
                    //     var item = document.createElement("div");
                    //     item.innerText = msg;
                    //     appendLog(item);
                    // }
                };

            } else {
                var item = document.createElement("div");
                item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
                appendLog(item);
            }
        }

        //link();

        let vueApp = createApp({
            delimiters:[`#{`,`}`],
            data() {
                return {
                    count: 0,
                    sendForm: [],
                    cmd: [
                        {
                            name: "echo",
                            template: [
                                {"type": "", "name": "cmd", "val": "1"},
                                {"type": "", "name": "data", "val": ""},
                            ]
                        },
                        {
                            name: "login",
                            template: [
                                {"type": "", "name": "cmd", "val": "100"},
                                {"type": "", "name": "token", "val": ""},
                            ]
                        },
                        {
                            name: "chatroomMember",
                            template: [
                                {"type": "", "name": "cmd", "val": "102"},
                            ]
                        },
                        {
                            name: "chatroomMsgSend",
                            template: [
                                {"type": "", "name": "cmd", "val": "121"},
                                {"type": "", "name": "msg", "val": ""},
                            ]
                        },
                        {
                            name: "privateMsgSend",
                            template: [
                                {"type": "", "name": "cmd", "val": "122"},
                                {"type": "", "name": "talk_id", "val": ""},
                                {"type": "", "name": "to_uuid", "val": ""},
                                {"type": "", "name": "to_name", "val": ""},
                                {"type": "", "name": "from_uuid", "val": ""},
                                {"type": "", "name": "from_name", "val": ""},
                                {"type": "", "name": "msg", "val": ""},
                            ]
                        },
                    ],
                    curCmd:"NONE",
                }
            },
            methods: {
                link: function () {
                    console.log("link")
                    if (conn && conn.readyState == WebSocket.OPEN) {
                        console.log("conn open")
                        return
                    }
                    link();
                },
                close: function () {
                    console.log("close")
                    conn.close();
                },
                cleanLog:function () {
                    log.innerHTML = "";
                },
                selectCmd:function () {
                    console.log(this.curCmd)
                    if (this.curCmd=="NONE"){
                        return;
                    }
                    let selectCmd = this.cmd[this.curCmd]['template'];
                    console.log(selectCmd)
                    this.sendForm = JSON.parse(JSON.stringify(selectCmd))
                },
                add: function () {
                    console.log("add")

                    this.sendForm.push({
                        "type": "",
                        "name": "",
                        "val": "",
                    })
                },
                del: function (k) {
                    this.sendForm.splice(k, 1)
                },
                cleanVal: function (k) {
                    this.sendForm[k]["val"] = ""
                },
                clean: function (k) {
                    this.sendForm = []
                },
                send: function () {
                    console.log("send")
                    let sendData = {}
                    if (this.sendForm) {
                        for (let i of this.sendForm) {
                            let val = i.val
                            if (i.type == "i") {
                                val = parseInt(val)
                            }
                            sendData[i.name] = val
                        }
                    }

                    if (conn.readyState != WebSocket.OPEN) {
                        console.log("no conn")
                        return
                    }
                    console.log("send data", sendData)
                    let sendStr = JSON.stringify(sendData);
                    conn.send(sendStr);
                }
            },
        }).mount('#app')
    };
</script>

</html>
